package com.app.util.common;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;

/**
 * 下载文件
 */
public class FileDownload {

	/**
	 * @param response 
	 * @param filePath		//文件完整路径(包括文件名和扩展名)
	 * @param fileName		//下载后看到的文件名
	 * @return  文件名
	 */
	public static void fileDownload( final HttpServletRequest request,final HttpServletResponse response, String filePath, String fileName) throws Exception{  
		    byte[] data = FileUtil.toByteArray2(filePath); 
		    //fileName=new String(fileName.getBytes(),"ISO-8859-1");
		    //fileName = URLEncoder.encode(fileName, "UTF-8");  
		    
		    UserAgent userAgent = UserAgent.parseUserAgentString(request==null?"":request.getHeader("User-Agent"));
		    response.reset();  
		    if(userAgent.getBrowser().getGroup() == Browser.FIREFOX) {
        		response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''"+URLEncoder.encode(fileName,"UTF-8").replaceAll("\\+", "%20") );
        	}else {
                response.setHeader( "Content-Disposition", "attachment;filename="  + new String( fileName.getBytes("gbk"), "ISO8859-1" ) );
        	}
		    response.addHeader("Content-Length", "" + data.length);  
		    
		    Path path = Paths.get(filePath);  
		    String contentType = Files.probeContentType(path); 
		    
		    if(filePath.endsWith(".ofd")||filePath.endsWith(".OFD")){
		    	response.setContentType("application/ofd;");
		    }else{
		    	response.setContentType(contentType);
		    }  
		    
		    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
		    outputStream.write(data);  
		    outputStream.flush();  
		    outputStream.close();
		    response.flushBuffer();
		    
		} 

}
